<template>
  <div class="register">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      label-position="right"
      label-width="0px"
      class="register-form position-middle-center"
    >
      <h3 class="title">注册账户</h3>
      <el-form-item prop="name" label="姓名" :label-width="labelWidth">
        <el-input
          v-model="loginForm.name"
          type="text"
          auto-complete="off"
          placeholder="请输入姓名"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item prop="username" label="用户名" :label-width="labelWidth">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="请输入用户名"
          maxlength="20"
        ></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机号" :label-width="labelWidth">
        <el-input
          v-model="loginForm.phone"
          type="text"
          auto-complete="off"
          placeholder="请输入手机号"
          maxlength="11"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code" label="验证码" :label-width="labelWidth">
        <div class="fl" style="width:65%">
          <el-input
            v-model="loginForm.code"
            type="text"
            auto-complete="off"
            placeholder="请输入验证码"
            maxlength="6"
          ></el-input>
        </div>
        <div class="fr" style="width:34%">
          <el-button
            :loading="getCodeLoading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="getCode"
          >
            <span>{{codeStatusText}}</span>
          </el-button>
        </div>
      </el-form-item>
      <el-form-item prop="email" label="邮箱" :label-width="labelWidth">
        <el-input v-model="loginForm.email" type="text" auto-complete="off" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item class="position-re" prop="password" label="密码" :label-width="labelWidth">
        <el-input
          v-model="loginForm.password"
          :type="isEye?'text':'password'"
          auto-complete="off"
          placeholder="请输入密码"
          @keyup.enter.native="handleLogin"
        ></el-input>
        <span :class="['eye',{'on':isEye}]" @click="()=>{isEye = !isEye;}">
          <i class="el-icon-view"></i>
        </span>
      </el-form-item>
      <el-form-item :label-width="labelWidth" label="地址">
        <city :addr_this="addr_this" :citys="citys" ref="city"></city>
      </el-form-item>
      <el-form-item :label-width="labelWidth">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
      </el-form-item>
      <div class="pb20 clear">
        <span class="fr">
          <em class="fz12">已有账号</em>
          <router-link class="c-main" to="/login">去登陆</router-link>
        </span>
      </div>
    </el-form>
  </div>
</template>

<script>
import { _getCode, _register } from "@/http/ajax";
import * as MDZZ from "@/http/reg";
import city from "@/components/citys/index.vue";
export default {
  name: "Reigster",
  components: { city },
  data() {
    const validName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("姓名不能为空"));
      } else if (!MDZZ.zhongwe(value)) {
        callback(new Error("格式格式不对（姓名为中文）"));
      } else {
        callback();
      }
    };
    const validUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("用户名不能为空"));
      } else if (!MDZZ.shuziyingwen(value)) {
        callback(new Error("用户名格式不对（只能是数字、字母组成）"));
      } else {
        callback();
      }
    };
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("手机号不能为空"));
      } else if (!MDZZ.shoujihao(value)) {
        callback(new Error("手机号格式不对"));
      } else {
        callback();
      }
    };
    const validCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("验证码不能为空"));
      } else if (!MDZZ.yanzhengma(value)) {
        callback(new Error("验证码格式不对"));
      } else {
        callback();
      }
    };
    const validYouxiang = (rule, value, callback) => {
      if (!value) {
        callback(new Error("邮箱不能为空"));
      } else if (!MDZZ.emailNumber(value)) {
        callback(new Error("邮箱格式不对"));
      } else {
        callback();
      }
    };
    const validMima = (rule, value, callback) => {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else if (!MDZZ.shuziyingwen(value)) {
        callback(new Error("密码格式不对"));
      } else {
        callback();
      }
    };
    return {
      addr_this: this,
      citys: {
        provinceId: 0,
        cityId: 0,
        districtId: 0
      },
      labelWidth: "80px",
      codeUrl: "",
      loginForm: {
        name: "",
        username: "",
        phone: "",
        password: "",
        code: "",
        email: "",
        enabled: true,
        provinceId: "",
        cityId: "",
        districtId: ""
      },
      loginRules: {
        name: [{ required: true, trigger: "blur", validator: validName }],
        username: [
          { required: true, trigger: "blur", validator: validUsername }
        ],
        phone: [{ required: true, trigger: "blur", validator: validPhone }],
        code: [{ required: true, trigger: "blur", validator: validCode }],
        email: [{ required: true, trigger: "blur", validator: validYouxiang }],
        password: [{ required: true, trigger: "blur", validator: validMima }]
      },
      loading: false,
      getCodeLoading: false,
      codeStatusText: "获取验证码",
      codeTimer: null,
      codeFlag: true,
      redirect: undefined,
      isEye: false
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    isvalidName(str) {
      const reg = /^[0-9a-zA-Z]*$/g;
      return reg.test(str);
    },
    isvalidPhone(str) {
      const reg = /^1[3456789]\d{9}$/g;
      return reg.test(str);
    },
    isvalidCode(str) {
      const reg = /^[0-9]*$/g;
      return reg.test(str);
    },
    getCode() {
      this.$refs.loginForm.validateField(['phone'], valid => {
        var user = this.loginForm;
        if (!valid) {
          if (!this.codeFlag) {
            return;
          }
          this.codeFlag = false;
          this.getCodeLoading = true;
          this.codeStatusText = "获取中...";
          _getCode(
            { phone: this.loginForm.phone, content: "register" },
            res => {
              this.codeFlag = true;
              this.getCodeLoading = false;
              this.codeStatusText = "获取成功";
              let t = 60;
              this.codeTimer = setInterval(() => {
                t--;
                if (t < 0) {
                  clearInterval(this.codeTimer);
                  this.codeStatusText = "重新获取";
                } else {
                  this.codeStatusText = t + "s后重新获取";
                }
              }, 1000);
            },
            err => {
              this.getCodeLoading = false;
              this.codeFlag = true;
              this.codeStatusText = "重新获取";
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        var user = this.loginForm;
         console.log(valid)
        if (valid) {
          this.loading = true;
          let _this = this;
          _register(
            user,
            res => {
              this.loading = false;
              this.$router.replace("/login");
            },
            err => {
              this.loading = false;
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.codeTimer);
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  position: relative;
  height: 100%;
  background-image: url(https://docs-1255840532.cos.ap-shanghai.myqcloud.com/3968.jpg);
  background-size: cover;
  .eye {
    position: absolute;
    right: 0;
    top: 0;
    font-size: 20px;
    padding: 0 10px;
    cursor: pointer;
    &.on {
      color: blue;
    }
  }
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 540px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  display: inline-block;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
